﻿using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using System.Windows.Forms;
using System.IO;
using System.ComponentModel;
using EnvDTE;
using System.Collections.Generic;

namespace Company.vsEnv
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the information needed to show this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    [Guid(GuidList.guidvsEnvPkgString)]
    [ProvideAutoLoad("{D2567162-F94F-4091-8798-A096E61B8B50}")]
    [ProvideOptionPage(typeof(OptionPageCustom), "Environment", "Environment Variables", 0, 0, true)]
    public sealed class vsEnvPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public vsEnvPackage()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        OptionPageCustom optionPage;

        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();
            var sln = GetService(typeof(SVsSolution)) as IVsSolution;
            uint o;
            var mgr = new LoadManager();
            sln.SetProperty((int)__VSPROPID4.VSPROPID_ActiveSolutionLoadManager, mgr);
            optionPage = (OptionPageCustom)GetDialogPage(typeof(OptionPageCustom));
            optionPage.DTE = (DTE)GetService(typeof(DTE));
            sln.AdviseSolutionEvents(new SolutionLoadEventListener(optionPage), out o);
            MessageBox.Show(optionPage.DTE.CommandLineArguments);
        }
        #endregion
    }

    public class SolutionLoadEventListener : IVsSolutionLoadEvents, IVsSolutionEvents
    {
        private OptionPageCustom optionPage;
        public SolutionLoadEventListener(OptionPageCustom optionPage)
        {
            this.optionPage = optionPage;
        }

        public int OnAfterBackgroundSolutionLoadComplete()
        {
            return 0;
        }

        public int OnAfterLoadProjectBatch(bool fIsBackgroundIdleBatch)
        {
            return 0;
        }

        public int OnBeforeBackgroundSolutionLoadBegins()
        {
            return 0;
        }

        public int OnBeforeLoadProjectBatch(bool fIsBackgroundIdleBatch)
        {
            return 0;
        }

        public int OnBeforeOpenSolution(string pszSolutionFilename)
        {
            string text = optionPage.Variables;

            Dictionary<string, Dictionary<string, string>> folders;
            string message;
            if (Helper.TryParseIni(text, out folders, out message))
            {
                foreach (string key in folders.Keys)
                {
                    if (pszSolutionFilename.StartsWith(key, true, CultureInfo.InvariantCulture))
                    {
                        foreach (var variable in folders[key])
                        {
                            Environment.SetEnvironmentVariable(variable.Key, variable.Value);
                        }
                        break;
                    }
                }
            }

            return 0;
        }

        public int OnQueryBackgroundLoadProjectBatch(out bool pfShouldDelayLoadToNextIdle)
        {
            pfShouldDelayLoadToNextIdle = false;
            return 0;
        }

        public int OnAfterCloseSolution(object pUnkReserved)
        {
            return 0;

        }

        public int OnAfterLoadProject(IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy)
        {
            return 0;
        }

        public int OnAfterOpenProject(IVsHierarchy pHierarchy, int fAdded)
        {
            return 0;
        }

        public int OnAfterOpenSolution(object pUnkReserved, int fNewSolution)
        {
            return 0;
        }

        public int OnBeforeCloseProject(IVsHierarchy pHierarchy, int fRemoved)
        {
            return 0;
        }

        public int OnBeforeCloseSolution(object pUnkReserved)
        {
            return 0;
        }

        public int OnBeforeUnloadProject(IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy)
        {
            return 0;
        }

        public int OnQueryCloseProject(IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel)
        {
            return 0;
        }

        public int OnQueryCloseSolution(object pUnkReserved, ref int pfCancel)
        {
            return 0;
        }

        public int OnQueryUnloadProject(IVsHierarchy pRealHierarchy, ref int pfCancel)
        {
            return 0;
        }
    }

    public class LoadManager : IVsSolutionLoadManager
    {
        public int OnBeforeOpenProject(ref Guid guidProjectID, ref Guid guidProjectType, string pszFileName, IVsSolutionLoadManagerSupport pSLMgrSupport)
        {
            return 0;
        }

        public int OnDisconnect()
        {
            return 0;
        }
    }

    [ClassInterface(ClassInterfaceType.AutoDual)]
    [Guid("E63B1A91-A9CE-4597-8689-1125CFA96708")]
    public class OptionPageCustom : DialogPage
    {
        public DTE DTE { get; set; }
        private string _variables;

        public string Variables
        {
            get { return _variables; }
            set { _variables = value; }
        }

        public override void ResetSettings()
        {
            Variables =
@"[D:\folder\]
key=value
";
        }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
        }

        protected override void OnApply(DialogPage.PageApplyEventArgs e)
        {
            if (e.ApplyBehavior == ApplyKind.Apply)
            {
                Variables = ctl.VariableText;

                if (!string.IsNullOrEmpty(DTE.Solution.FullName))
                {
                    Dictionary<string, Dictionary<string, string>> folders;
                    string message;
                    if (Helper.TryParseIni(Variables, out folders, out message))
                    {
                        foreach (string key in folders.Keys)
                        {
                            if (DTE.Solution.FullName.StartsWith(key, true, CultureInfo.InvariantCulture))
                            {
                                foreach (var variable in folders[key])
                                {
                                    Environment.SetEnvironmentVariable(variable.Key, variable.Value);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                ctl.VariableText = Variables;
            }
            base.OnApply(e);
        }

        protected override void OnActivate(CancelEventArgs e)
        {
            ctl.VariableText = Variables;
            base.OnActivate(e);
        }

        protected override void OnDeactivate(CancelEventArgs e)
        {
            Dictionary<string, Dictionary<string, string>> temp;
            string message;
            if (!Helper.TryParseIni(ctl.VariableText, out temp, out message))
            {
                MessageBox.Show(message, "Invalid configuration", MessageBoxButtons.OK, MessageBoxIcon.Error);
                e.Cancel = true;
            }
            else
            {
                Variables = ctl.VariableText;
            }
            base.OnDeactivate(e);
        }
        public OptionPageCustom()
        {
            ResetSettings();
        }

        MyControl ctl;

        protected override IWin32Window Window
        {
            get
            {
                ctl = new MyControl();
                ctl.VariableText = Variables;
                return ctl;
            }
        }
    }


}
